//
//  SearchViewController.swift
//  miaoyin
//
//  Created by David on 2017/3/9.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

@objc protocol SearchViewControllerDelegate {
    @objc optional func searchViewController(_ vc: SearchViewController, didSelectSearchFile filename: String?, fileID: String?, filePage: String?)
}

class SearchViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var tableView: UITableView!
    
    var searchInput: UITextField!
    
    var searchResult: NSArray?
    
    var delegate: SearchViewControllerDelegate?
    
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        tableView = UITableView(frame: CGRect(x: 0, y: 64, width: view.frame.width, height: view.frame.height))
        tableView.tableFooterView = UIView(frame: CGRect.zero)
        tableView.keyboardDismissMode = .onDrag
        self.tableView.delegate = self
        self.tableView.dataSource = self
        view.addSubview(tableView)
        
        let searchView = UIView(frame: CGRect(x: 16, y: 8, width: view.frame.width - 80, height: 28))
        searchView.layer.cornerRadius = 4
        searchView.backgroundColor = UIColor.white
        
        
        searchInput = UITextField(frame: CGRect(x: 16, y: 0, width: searchView.frame.width - 16, height: 28))
        searchInput.font = UIFont.systemFont(ofSize: 14)
        searchInput.placeholder = "搜索文件"
        searchView.addSubview(searchInput)
        searchInput.clearButtonMode = .always
        searchInput.returnKeyType = .search
        searchInput.enablesReturnKeyAutomatically = true
        searchInput.addTarget(self, action: #selector(SearchViewController.searchComfirm), for: .editingDidEndOnExit)
        
        let navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64))
        view.addSubview(navigationBar)
        navigationBar.barStyle = .black
        navigationBar.barTintColor = themeColor2
        navigationBar.tintColor = UIColor.white
        let navItem = UINavigationItem(title: "")
        navigationBar.pushItem(navItem, animated: false)
        navItem.leftBarButtonItem = UIBarButtonItem(customView: searchView)
        
        navItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: .plain, target: self, action: #selector(SearchViewController.close))
        
        searchInput.becomeFirstResponder()
    }

    func close(){
        dismiss(animated: false, completion: nil)
    }
    
    func searchComfirm(){
        print("doSearch")
        searchInput.resignFirstResponder()
        var resq = URLRequest(url: URL(string: "\(apiBaseDomainName)/?m=admin&c=user&a=searchFile")!)
        resq.httpMethod = "POST"
        resq.httpBody = "content=\(searchInput.text!)".data(using: .utf8)
        
        URLSession.shared.dataTask(with: resq) { (data:Data?, re:URLResponse?, er:Error?) in
            do{
                if er != nil{
                    throw er!
                }
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                self.searchResult = jsonObj?.object(forKey: "data") as? NSArray
                DispatchQueue.main.async {
                    
                    self.tableView.reloadData()
                }
                
            }catch let ex{
                print(ex)
            }
        }.resume()
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if searchResult != nil{
            if searchResult!.count > 0{
                return searchResult!.count
            }
        }
        return 1
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "item")
        
        
        if searchResult != nil{
            if searchResult!.count > 0{
                let fileItem = searchResult?.object(at: indexPath.row) as? NSDictionary
                cell.textLabel?.text = fileItem?.object(forKey: "filename") as? String
                return cell
            }else{
                cell.textLabel?.text = "没有找到相关结果"
            }
        }
        cell.textLabel?.lineBreakMode = .byTruncatingMiddle
        
        
        
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if searchResult != nil {
            if searchResult!.count > 0{
                let resItem = searchResult?.object(at: indexPath.row) as? NSDictionary
                let fileName = resItem?.object(forKey: "filename") as? String
                let fileID = resItem?.object(forKey: "itemid") as? String
                let filePage = resItem?.object(forKey: "num") as? String
                dismiss(animated: true, completion: nil)
                delegate?.searchViewController?(self, didSelectSearchFile: fileName, fileID: fileID, filePage: filePage)
            }
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
